package com.unknown

import org.apache.activemq.transport.TransportServerSupport
import org.eclipse.jetty.server.Server
import org.eclipse.jetty.server.Connector
import org.eclipse.jetty.server.bio.SocketConnector
import org.eclipse.jetty.server.handler.ContextHandler
import org.eclipse.jetty.server.session.SessionHandler
import org.eclipse.jetty.servlet.ServletHandler
import org.eclipse.jetty.servlet.ServletHolder
import org.eclipse.jetty.servlet.ServletMapping
import org.apache.activemq.util.ServiceStopper
import org.apache.activemq.command.BrokerInfo
import org.eclipse.jetty.servlet.ServletContextHandler

/**
 * Created by IntelliJ IDEA.
 * User: propatalent
 * Date: 10/26/11
 * Time: 10:23 PM
 * To change this template use File | Settings | File Templates.
 */
class WSTransportServer extends TransportServerSupport {
    private URI bindAddress;
     private Server server;
     private Connector connector;

     public WSTransportServer(URI location) {
         super(location);
         this.bindAddress = location;
     }

     protected void doStart() throws Exception {
         server = new Server();
         if (connector == null) {
             connector = new SocketConnector();
         }
         connector.setHost(bindAddress.getHost());
         connector.setPort(bindAddress.getPort());
         server.setConnectors([connector] as SocketConnector[]);

         ServletContextHandler contextHandler = new ServletContextHandler();
         contextHandler.setContextPath("/");
         contextHandler.setServer(server);
         server.setHandler(contextHandler);

         SessionHandler sessionHandler = new SessionHandler();
         contextHandler.setHandler(sessionHandler);

         ServletHandler servletHandler = new ServletHandler();
         sessionHandler.setHandler(servletHandler);

         ServletHolder holder = new ServletHolder();
         holder.setName("WSStomp");
         holder.setClassName(StompServlet.class.getName());
         servletHandler.setServlets([holder] as ServletHolder[]);

         ServletMapping mapping = new ServletMapping();
         mapping.setServletName("WSStomp");
         mapping.setPathSpec("/");
         servletHandler.setServletMappings([mapping] as ServletMapping[]);

         contextHandler.servletHandler = servletHandler
         contextHandler.setAttribute("acceptListener", getAcceptListener());

         server.start();
     }

     protected void doStop(ServiceStopper stopper) throws Exception {
         Server temp = server;
         server = null;
         if (temp != null) {
             temp.stop();
         }
     }

     public InetSocketAddress getSocketAddress() {
         return null;
     }

     public void setBrokerInfo(BrokerInfo brokerInfo) {
     }
}
